import Vue from 'vue';
import Vuex from 'vuex';
import cookie from 'js-cookie';
import {login, logout} from '@/api/login/login'
import {getMenus, getUserInfo} from "@/api/system/system";

Vue.use(Vuex);

let getToken = () => {
    return cookie.get('token');
}

const store = new Vuex.Store({
    state: {
        userInfo: {},
        token: getToken(),
        menus: undefined,
        permission: {}
    },
    getters: {
        token(state) {
            return state.token;
        },
        menus(state) {
            return state.menus;
        },
        permission(state) {
            return state.permission;
        },
        userInfo(state) {
            return state.userInfo;
        }
    },
    mutations: {
        setUserInfo(state, payload) {
            state.userInfo = payload;
        },
        setToken(state, payload) {
            if (payload === undefined || payload === "") {
                cookie.remove("token");
            } else {
                cookie.set("token", payload);
            }
            state.token = payload;
        },
        setPermission(state, payload) {
            state.permission = payload;
        },
        setMenus(state, payload) {
            state.menus = payload;
        },
        clearToken(state) {
            cookie.set("token", null);
            state.token = null;
        }
    },
    actions: {
        Login({commit}, loginUser) {
            return new Promise((resolve, reject) => {
                login(loginUser).then(rsp => {
                    commit("setToken", rsp.access_token);
                    resolve(rsp);
                }).catch(error => {
                    reject(error);
                })
            });
        },
        Logout({commit}) {
            return new Promise((resolve, reject) => {
                logout().then(() => {
                    commit("setToken", undefined);
                    resolve();
                }).catch(() => {
                    commit("setToken", undefined);
                    reject();
                })
            });
        },
        GetUserInfo({commit, state}) {
            if (state.userInfo.id) {
                return new Promise((resolve) => {
                    resolve(state.userInfo);
                });
            } else {
                // 后台查询用户信息
                return new Promise((resolve, reject) => {
                    getUserInfo().then(rsp => {
                        commit("setUserInfo", rsp.data);
                        resolve(rsp.data);
                    }).catch(reason => {
                        reject(reason);
                    })
                });
            }
        },
        GetMenus({commit, state}) {
            return new Promise(resolve => {
                getMenus().then(value => {
                    commit("setMenus", value)
                    resolve(state.menus);
                });
            })
        }
    }
});


export default store;